package com.eesujie.xcs.controller;

import com.eesujie.xcs.common.Result;
import com.eesujie.xcs.common.UserContext;
import com.eesujie.xcs.entity.dto.NoteCommentDTO;
import com.eesujie.xcs.entity.dto.NoteDTO;
import com.eesujie.xcs.entity.po.NoteCommentPO;
import com.eesujie.xcs.service.NoteCommentService;
import com.eesujie.xcs.service.NoteImageService;
import com.eesujie.xcs.service.NoteService;
import com.eesujie.xcs.util.JsonUtils;
import com.eesujie.xcs.util.MinioUtils;
import com.eesujie.xcs.util.PojoUtils;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 笔记表 前端控制器
 * </p>
 *
 * @author eesujie
 * @since 2023-04-19
 */
@RestController
@RequestMapping("/note")
public class NoteController {
    @Resource
    private NoteService noteService;

    @Resource
    private NoteImageService noteImagesService;

    @Resource
    private NoteCommentService noteCommentService;

    @Resource
    private MinioUtils minioUtils;

    private static final String NOTE_IMAGE_BUCKET = "note-images";

    @GetMapping("/getAll")
    public Result getAllNotes() {
        var voList = noteService.getAllNotes();
        return Result.success(voList);
    }

    @GetMapping("/getComments")
    public Result getComments(Long noteId) {
        var list = noteCommentService.getCommentsByNoteId(noteId);
        return Result.success(list);
    }


    @PostMapping("/comment")
    public Result comment(@RequestBody NoteCommentDTO noteCommentDTO) {
        NoteCommentPO noteCommentPO = PojoUtils.parsePO(noteCommentDTO);
        noteCommentPO.setUserId(UserContext.getUserId());
        noteCommentService.save(noteCommentPO);
        return Result.success();
    }


    @GetMapping("/getImages")
    public Result getImages(Long noteId) {
        var list = noteImagesService.getImagesByNoteId(noteId);
        return Result.success(list);
    }

    @PostMapping("/publish")
    public Result publish(@RequestBody NoteDTO noteDTO) {
        noteService.publishNote(noteDTO);
        return Result.success();
    }

    @PostMapping("/uploadImage")
    public Result uploadImage(MultipartFile file) {
        return Result.success(minioUtils.upload(NOTE_IMAGE_BUCKET, file));
    }

    @PostMapping("/deleteImage")
    public Result deleteImage(String imageUrl) {
        minioUtils.delete(NOTE_IMAGE_BUCKET, imageUrl);
        return Result.success();
    }
}
